<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->load->model("User_model");
		$this->load->helper("form");
		$this->load->library("form_validation");
		$this->load->library("email");
	}
	
	function index(){
		$data['title']= "CIPOST :: Inicio";
		$data['activo'] = "inicio";
		$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
		$data['main_content']="/inicio/index";
        $this->load->view('includes/template',$data);
	}

	function login($mesg=''){
		$data['title']='CIPOST :: Logueo de Usuario';
		$data['activo'] = "inicio";
		$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
		$data['main_content']='/user/loguin';
		$data['msg']=$mesg;
		$this->load->view('includes/template',$data);
	}
	
	function verify_loguin(){
		$this->form_validation->set_rules('username','Nombre de Usuario','trim|required|alpha_numeric|xss_clean');
		$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
		$username=$this->input->post('username');
		$password=md5($this->input->post('password'));
		$loguin=$this->User_model->verify_loguin($username,$password);
		if($loguin){
			$datos=array(
				'is_logued_in'=>TRUE,
				'nombre_usuario'=>$loguin[0]->nombre,
				'id'=>$loguin[0]->cod_usuario,
				'tipo'=>$loguin[0]->tipo);
		$this->session->set_userdata($datos);
		redirect('/index.php/inicio');
		}
		else{
			$msg='Usuario no encontrado o contraseña incorrecta';
			$this->login($msg);
		}	
	}
	
	function logout(){
		$this->session->sess_destroy();
		redirect('/index.php/user/login');
	}
	
	function retry_password(){
		
	}
	
	function register(){
		if($this->session->userdata('is_logued_in') && (($this->session->userdata('tipo')=="user") or ($this->session->userdata('tipo')=="docente")))
		{
			$data['title']= "CIPOST :: Inicio";
			$data['activo'] = "inicio";
			$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
			$data["mensaje"] = 'Error, Usted ya ha iniciado Sesi&oacute;n, no se puede realizar la operacion de Registro';
			$data['main_content']="/inicio/index";
            $this->load->view('includes/template',$data);
		}
		else
		{
		$data['title']='CIPOST :: Registro de Alumno';
		$data['activo'] = "inicio";
		$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
		$data['main_content']='user/register';
		$this->load->view('includes/template',$data);
		}
	}
	
	function create_account(){
		$this->form_validation->set_rules('username','Nombre de Usuario','required|trim|min_length[4]|callback__username_check');
		$this->form_validation->set_rules('apellidos','Apellidos','required|trim|min_length[4]');
		$this->form_validation->set_rules('nombres','Nombres','required|trim|min_length[4]');
		$this->form_validation->set_rules('direccion','Direccion','required|trim|min_length[8]');
		$this->form_validation->set_rules('dni','DNI','required|trim|min_length[8]|max_length[8]');
		$this->form_validation->set_rules('telefono','Telefono','required|trim|min_length[6]');
		$this->form_validation->set_rules('email','E-mail','required|trim|valid_email|callback__email_check');
		$this->form_validation->set_rules('password', 'Contraseña', 'required|md5');
		$this->form_validation->set_rules('repassword', 'Confirmar Contraseña', 'required|matches[password]|md5');
		$this->form_validation->set_message('required','El campo %s es requerido');
		$this->form_validation->set_message('valid_email','El campo %s no es válido');
		$this->form_validation->set_message('min_length','El campo %s debe tener mínimo caracteres');
		$this->form_validation->set_message('_username_check','El %s ya existe.');
		$this->form_validation->set_message('_email_check','El %s ya se encuentra registrado.');
		$this->form_validation->set_message('matches','Las constraseñas no coinciden.');
		if ($this->form_validation->run() == FALSE)
		{
			$this->register();
		}
		else
		{
			$username=$this->input->post('username');
			$password=$this->input->post('password');
			$email=$this->input->post('email');
			$activation_code=$this->_random_string(10);
			$nombres=$this->input->post('nombres');
			$apellidos=$this->input->post('apellidos');
			$dni=$this->input->post('dni');
			$direccion=$this->input->post('direccion');
			$telefono=$this->input->post('telefono');
			$insert=$this->User_model->insert_user($username,$password,$activation_code,$email,$nombres,$apellidos,$dni,$direccion,$telefono);		
		$config['mailtype'] = "html";
		$this->email->initialize($config);
		$this->email->from("soporte@cipost.com","CIPOST");
		$this->email->to($email);
		$this->email->subject("Verificacion de Registro CIPOST");
		$this->email->message("Por Favor de verificar su registro".anchor("http://localhost:8080/cipost/user/register_confirm/".$activation_code,"Confirmar Registro"));
		$this->email->send();
		redirect('/index.php/user/login');
		}
	}
	function register_confirm($activation_code=''){
		$activation_code = $this->uri->segment(3);
		if($activation_code=='')
			die("C&oacute;digo de verificaci&oacute;n errado.");
		else{
			$update=$this->User_model->confirm_registration($activation_code);
			if($update){
				$data['title']= "CIPOST :: Inicio";
				$data['activo'] = "inicio";
				$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
				$data["mensaje"] = "Registro completo.";
				$data['main_content']="inicio/index";
	            $this->load->view('includes/template',$data);
			}
			else{
				$data['title']= "CIPOST :: Inicio";
				$data['activo'] = "inicio";
				$data['nombresession'] = $this->User_model->nombresession($this->session->userdata('id'))->row();
				$data["mensaje"] = "Su verificaci&oacute;n de Registro Fall&oacute;.";
				$data['main_content']="inicio/index";
	            $this->load->view('includes/template',$data);
			}
		}
	}
	
	function _username_check($username){
		return $this->User_model->username_check($username);
	}
		
	function _email_check($email){
		return $this->User_model->email_check($email);
	}
	
	
	
	function _random_string($length){
		$len = $length;
		$base='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';
		$max=strlen($base)-1;
		$activatecode = '';
		mt_srand((double)microtime()*1000000);
		while(strlen($activatecode) < $len)
		{
			$activatecode .= $base{mt_rand(0,$max)};
		}
		return $activatecode;	
	}
	
	function username_check_ajax(){
		echo $this->input->post('nombre_usuario');
		if($this->input->is_ajax_request()){
			$username=$this->input->post('nombre_usuario');
			if($this->User_model->username_check($username)){
				echo "TRUE";
			}
			else{
				echo "FALSE";
			}
		}
	}
}

?>